import router from '@/router'
import pinia from '@/store'
import useUserStore from '@/store/modules/user.ts'
let userStore = useUserStore(pinia)
// import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
// nprogress.configure({ showSpinner: false })
router.beforeEach(async (to: any, _: any, next: any) => {
  // nprogress.start()
  if (userStore.token) {
    if (to.path == '/login') {
      next('/')
    } else {
      if (userStore.username) {
        next()
      } else {
        try {
          await userStore.getUserInfo()
          //万一:刷新的时候是异步路由,有可能获取到用户信息、异步路由还没有加载完毕,出现空白的效果
          next({ ...to })
        } catch (err) {
          // 获取不到用户信息，token过期或者用户修改token
          await userStore.logOut()
          next({ path: '/login', query: { paths: to.path } })
        }
      }
    }
  } else {
    if (to.path == '/login') {
      next()
    } else {
      next({ path: '/login', query: { paths: to.path } })
    }
  }
})
router.afterEach(() => {
  // nprogress.done()
})
